package com.titan.core.utils.data;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.jaxen.JaxenConstants;
import org.jaxen.javabean.Element;
import org.jaxen.javabean.ElementIterator;
import org.jaxen.util.SingleObjectIterator;

import com.titan.core.utils.io.ConsoleUtils;
import com.titan.core.utils.object.ListSet;

public class JaxenUtils {
    public static void print(String prefix, Object object) {
        if (object == null) {
            ConsoleUtils.log(prefix, "object", null);
            return;
        }
        ConsoleUtils.log(prefix, "clazz", object.getClass(), "object", object);
        if (object instanceof org.jaxen.javabean.Element) {
            org.jaxen.javabean.Element element = (org.jaxen.javabean.Element) object;
            ConsoleUtils.log("org.jaxen.javabean.Element", "name", element.getName());
            print("org.jaxen.javabean.Element", element.getObject());
        } else if(object instanceof List) {
            List list = (List)object;
            if(list.size()==0) {
                ConsoleUtils.log(object.getClass().getName(), "object", "集合为空！");
            }
            for (int i = 0; i < list.size(); i++) {
                Object item = list.get(i);
                ConsoleUtils.log(object.getClass().getName()+"["+i+"]", "clazz", item.getClass(), "object", item);
            }
        }
    }

    public static Iterator<?> createIterator(Element parent, String localName, Object child) {
        if (child == null) {
            return JaxenConstants.EMPTY_ITERATOR;
        }
        if (child instanceof Collection) {
            Collection<?> collection = (Collection<?>)child;
            return new ElementIterator(parent, localName, collection.iterator());
        } else if (child.getClass().isArray()) {
            Object[] array = (Object[])child;
            Iterator<?> iterator = Arrays.asList(array).iterator();
            return new ElementIterator(parent, localName, iterator);
        } else if(child instanceof ListSet) {
            ListSet<?> children = (ListSet<?>)child;
            Iterator<?> iterator = children.toSet().iterator();
            return new ElementIterator(parent, localName, iterator);
        }
        return new SingleObjectIterator(new Element(parent, localName, child));
    }

}
